var app = getApp();
var _PAGE = 1;
var _PAGESIZE = 10;
var util = require("../../utils/util.js");
var mta = require('../../utils/mta_analysis.js');
var loads=true;
var startX = '', startY = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    paymentImg: app.globalData._network_path + 'payment_img.png',
    circleBg:["#E8E5FA","#FBF3CD","#FBE8E4","#E8E5FA","#FAEACE"],
    drawBg:["#1471FC","#FFDF40","#FA5D3A","#CE32FB","#FFAF23"],
    equipment_num:0,
    equipment: [],
    code_id:'',
    contract_id: '',
    code_name: '', //缴费器名称
    info:{},
    addpopup:false,
    name:"",
    index:0,
    hasMore: false,
    loading: false,
    loadShow: false,
    open: false,//开关
    openfirst: true,//防止频繁点击
    login_status:false,
    is_delete: false,//是否删除只剩一台缴费器
    is_load:false,
    showGuide:false,
    phone: '', //客服电话
    device_no:''
  },
  onLoad:function(options){
    // var showGuide=wx.getStorageSync('showGuide');
    // this.setData({ showGuide});
    // if (showGuide){
    //   wx.hideTabBar();
    // }else{
    //   wx.showTabBar();
    // }
    mta.Page.init();
    var pid = '',that=this,way='';
    var pro = '';//推广商ID
    var cha = '';//渠道ID
    var is_move = wx.getStorageSync('is_move');
    var is_click = wx.getStorageSync('is_click');
    //二维码进入获取参数
    if (util.isExitsVariable(options.scene)) {
      var scene = util.sceneToArr(decodeURIComponent(options.scene));
      console.log(scene,"scne")
      if (util.isExitsVariable(scene.pid)) {
        pid = scene.pid;
        way = scene.way;
      }
      //推广商ID
      if (util.isExitsVariable(scene.pro)) {
        pro = scene.pro;
      }
      //渠道ID
      if (util.isExitsVariable(scene.cha)) {
        cha = scene.cha;
      }

    }
    if (util.isExitsVariable(options.pid)) {
      pid = options.pid;
      way = options.way;
    }
    //渠道ID
    if (util.isExitsVariable(options.pro)) {
      pro = options.pro;
    }
    //渠道ID
    if (util.isExitsVariable(options.cha)) {
      cha = options.cha;
    }
    if (pid != '') {
      wx.setStorageSync("pid", pid);
      wx.setStorageSync("way", way);
    }
    if(pro!=''){
      wx.setStorageSync("promoter", pro);//推广商ID
    }
    if (cha != '') {
      wx.setStorageSync("channel", cha);//渠道ID
    }
    that.getPhone()//获取客服电话
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    var that = this;
    _PAGE = 1;
    that.setData({
      equipment_num: 0,
    })
    app.loginStatus(function(){
      that.setData({
        login_status: true
      })
      that.userBindEquipment();
    },function(){
      that.setData({
        login_status: false,
        loadShow: true
      })
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.setData({
      loadShow: false
    })
    loads=true
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    if (that.data.equipment_num == 1) {
      that.equipmentDetail();
      return false;
    }
    _PAGE = 1;
    that.userBindEquipment();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (that.data.equipment_num < 1) {
      return false;
    }
    if (!that.data.hasMore) {
      return false;
    }
    _PAGE++;
    that.setData({
      loading: true
    })
    that.userBindEquipment();
  },

  //登录
  login(){
    wx.navigateTo({
      url: '/pages/user/login/login',
    })
  },
  //跳转到 添加缴费器
  chooseFacility() {
    var token = wx.getStorageSync('token');
    //添加缴费器必须登录
    if (!util.isExitsVariable(token)) {
      wx.navigateTo({
        url: '/pages/user/login/login',
      })
      return false;
    }
    wx.navigateTo({
      url: '../addEquipment/addEquipment',
    })
  },

  //绑定列表
  userBindEquipment:function(){
    var that = this;
    app.ajax({
      url: 'User/Equipmentlists/userBindEquipment',
      load: loads,
      data: { page: _PAGE, pageSize: _PAGESIZE },
      success: function (res) {
        wx.stopPullDownRefresh();
        if (res.data.code == 1000) {
          wx.setStorageSync('equipment_num', res.data.data.length);
          //若只有一台缴费器直接到详情页，否则列表页
          var equipment_num = that.data.equipment_num + res.data.data.length;
          that.setData({
            equipment_num: equipment_num
          })

          if(equipment_num==1){
            that.setData({
              code_id: res.data.data[0].code_id,
              contract_id: res.data.data[0].contract_id,
            });
            that.equipmentDetail();
          }else if(equipment_num>1){
              //处理数据
              if (_PAGE == 1) {
                that.setData({
                  equipment: res.data.data,
                });
              } else {
                that.setData({
                  equipment: that.data.equipment.concat(res.data.data)
                });
              }
              //是否需要加载更多
              var hasMore = true;
              if (res.data.data.length < _PAGESIZE) {
                hasMore = false;
              }
              that.setData({
                hasMore: hasMore,
                loading: false
              })
            loads=false;
            }
        }else{
          if (_PAGE == 1) {
            that.setData({
              equipment_num: 0,
              equipment:[],
              hasMore: false,
              loading: false,
              is_delete: false
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              is_delete: false
            })
          }

        }
        that.setData({
          loadShow: true
        })

      }

    })
  },
  //缴费器详情
  equipmentDetail: function () {
    var that = this;
    var code_id = that.data.code_id;
    var contract_id = that.data.contract_id;
    app.ajax({
      url: "User/Equipmentlists/equipmentDetail",
      data: { code_id: code_id, contract_id: contract_id },
      success: function (res) {
        wx.stopPullDownRefresh();
        if (res.data.code == 1000) {
          that.setData({
            info: res.data.data,
          })
        }
        that.setData({
          is_load:true
        })
      }
    })
  },
  // 开启添加弹窗
  addchannelpop: function (e) {
    var that = this;
    var code_id = e.currentTarget.dataset.code_id;
    var index = e.currentTarget.dataset.index;                 // 数组key值
    that.setData({
      addpopup: true,
      code_id: code_id,
      code_name: '',
      index:index
    })
    return false;
  },
  // 取消弹窗
  abolish() {
    var that = this;
    that.setData({
      addpopup: false
    })
  },
  //缴费器名称输入
  inputNameFun(e){
    var that = this;
    var name = e.detail.value;
    that.setData({
      code_name: e.detail.value
    })

  },
  //确认修改
  sureSubmit() {
    var that = this;
    var index = that.data.index;
    var code_id = that.data.code_id;
    var code_name = that.data.code_name;
    var alias_name = "equipment[" + index + "].code_name";

    app.ajax({
      url:'User/Equipmentlists/editName',
      data: { code_id: code_id, name: code_name},
      success:function(res){
        app.showToast(res.data.message);
        if(res.data.code==1000){
          if(that.data.equipment_num == 1){//单缴费器
            that.setData({
              ['info.code_name']: code_name,
            });
          } else { //多缴费器
            that.setData({
              [alias_name]: code_name,
            });
          }

        }
      }
    })
    that.setData({
      addpopup: false
    })
  },
  //跳转缴费器详情
  facilityDetail(e) {
    var that = this;
    var code_id = e.currentTarget.dataset.code_id;
    var contract_id = e.currentTarget.dataset.contract_id;
    wx.navigateTo({
      url: '../facilityDetail/facilityDetail?code_id=' + code_id + '&contract_id=' + contract_id,
    })
  },

  //开关
  chooseone(e) {
    var that = this, index = e.currentTarget.dataset.index, openfirst = that.data.openfirst;
    var device_no = e.currentTarget.dataset.device_no;
    that.setData({
      device_no:device_no
    })
    var status = this.data.info.equipment_lists[index].status;
    var switch_machine = this.data.info.equipment_lists[index].switch_machine;
    if (status == 1) {
      app.showToast("您的缴费器已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (openfirst == false) {
      app.showToast("为保护缴费器请勿频繁操作,请5秒后重试", 'none', 3000);
      return false;
    }
    var switch_machine_str = 'info.equipment_lists[' + index + '].switch_machine';
    if (switch_machine == 0) {
      that.powerOff(1)
      that.setData({
        [switch_machine_str]: 1,
        openfirst: false,
      })
    } else {
      that.powerOff(0)
      that.setData({
        [switch_machine_str]: 0,
        openfirst: false,
      })
    }
  },
  //发送指令
  //开关机
  powerOff(device_status){
    var that = this;
    var device_status = device_status;
    var sn = that.data.device_no;
    app.ajax({
      url:'Common/Device/switch_control',
      data: { "sn": sn, "device_status": device_status},
      success:function(res){
        wx.vibrateLong();
        app.showToast(res.data.message, 'none', 2500);
        setTimeout(() => {
          that.setData({
            openfirst: true
          })
        }, 5000);
      }
    })
  },
  //续费
  goRenew: function (e) {
    var code = e.currentTarget.dataset.code;
    wx.navigateTo({
      url: '../user/renew/renew?code=' + code,
    })
  },
  /**
* 计算滑动角度
* @param {Object} start 起点坐标
* @param {Object} end 终点坐标
*/
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.equipment.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      equipment: this.data.equipment
    })
    startX=e.changedTouches[0].clientX;
    startY=e.changedTouches[0].clientY;
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      // start_X = startX,//开始X坐标
      // start_Y = startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.equipment.forEach(function (v, i) {
      v.isTouchMove = false;
      if (Math.abs(angle) > 30) return;
      //滑动超过30度角 return
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      equipment: that.data.equipment
    })
  },
  //解绑
  flDetele(e){
    var that = this, code_id = e.currentTarget.dataset.code_id;
    wx.showModal({
      title: '是否解绑',
      content: '解绑之后将无法查看该缴费器信息',
      showCancel: true,
      cancelText: '算了吧',
      cancelColor: '#DF0101',
      confirmText: '解绑',
      confirmColor: '#FF9E7D',
      success: function (res) {
        //确定事件
        if (res.confirm == true) {
          app.ajax({
            url: 'User/Equipmentlists/unBindEquipment',
            data: { code_id: code_id },
            success: function (res) {
              if (res.data.code == 1000) {
                var equipment = that.data.equipment;
                if (equipment.length == 2) {
                  that.setData({
                    equipment_num: 0,
                    is_delete: true
                  })
                }
                that.userBindEquipment();//重新调取接口
                app.showToast('删除成功');
              } else {
                app.showToast(res.data.message);
              }
            }
          })
        }
        //取消事件
        if (res.cancel == true) {
        }
      },
    })
  },
  //客服
  helpCenter() {
    wx.navigateTo({
      url: '../customService/customService',
    })
  },
  //申请售后
  applyAfterSale: function (e) {
    var that = this;
    var code_id = e.currentTarget.dataset.code_id;
    var contract_id = e.currentTarget.dataset.contract_id;
    wx.navigateTo({
      url: '../user/applyAfterSale/applyAfterSale?code_id=' + code_id + '&contract_id=' + contract_id,
    })
  },
  //去商城
  goShop(){
    wx.switchTab({
      url:'../shopping/shoppingHome/shoppingHome'
    })
  },
  //浏览记录
  shareLogHistory() {
    var that = this;
    app.ajax({
      url: 'User/Browse/browseLog',
      method: "POST",
      data: { browse_page: 'pages/home/home' },//1是邀请好友 2分享详情
      success: function (res) {
        if (res.data.code = 1000) {

        } else {

        }
      }

    })
  },
  //关闭引导
  closeGuide(){
    wx.showTabBar();
    wx.setStorageSync('showGuide',false);
    this.setData({ showGuide:false})
  },
  //跳转 使用记录
  navUsageRecord(e) {
    wx.navigateTo({
      url: '../user/usageRecord/usageRecord?code=' + e.currentTarget.dataset.code,
    })
  },
  //跳转 缴费记录
  paymentRecord(e) {
    wx.navigateTo({
      url: '/pages/guidance/guidance?code=' + e.currentTarget.dataset.code,
    })
  },
  //获取客服电话
  getPhone: function () {
    var that = this;
    // Ajax请求
    app.ajax({
      url: 'Common/Common/getSystemConfig',
      data: { key: 'company_hotline' },
      success: function (res) {
        if (res.data.code == 1000) {
          var content = res.data.data;
          that.setData({
            phone: content,
          })
        }
      }
    })
  },
  //打电话
  callPhone(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
  },
})
